package imageclipper

import (
	"errors"
	"path"
	"path/filepath"
	"strconv"
	"strings"
)

/*
检测原图像的矩阵大小
	params:
		file_path: 文件路径
		extension: 文件扩展名
	returns:
		cols: 列
		rows: 行
		err: error
*/
func getSourceRect(file_path, extension string) (cols, rows int, err error) {
	matches, err := filepath.Glob(path.Join(file_path, "*."+extension))
	for _, m := range matches {
		fileName := filepath.Base(m)
		name := strings.ReplaceAll(fileName, path.Ext(fileName), "")
		names := strings.Split(name, "_")
		col, e := strconv.Atoi(names[0])
		if e != nil {
			return cols, rows, e
		}
		row, e := strconv.Atoi(names[1])
		if e != nil {
			return cols, rows, e
		}
		if col >= cols {
			cols = col + 1
		}
		if row >= rows {
			rows = row + 1
		}
	}
	return
}

/*
检测原图片文件的扩展名
	params:
		file_path: 文件路径
	returns:
		extension: 扩展名
		err: error
*/
func getSourceExtension(file_path string) (extension string, err error) {
	for _, ext := range extensions {
		matches, err := filepath.Glob(path.Join(file_path, "*."+ext))
		if err != nil {
			return extension, err
		}
		if len(matches) > 0 {
			extension = ext
			break
		}
	}
	if extension == "" {
		err = errors.New("get extension failed")
		return
	}
	return extension, nil
}
